<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 根据长度获取随机字符串
 * @param $length
 * @param bool $is_capital
 * @return null|string
 */
function getRandChar($length, $is_capital = false)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    if (!$is_capital) {
        $strPol .= "abcdefghijklmnopqrstuvwxyz";
    }

    $max = strlen($strPol) - 1;

    for ($i = 0;
         $i < $length;
         $i++) {
        $str .= $strPol[rand(0, $max)];
    }

    return $str;
}


/**
 * 加密指定字符串
 * @param string $token
 * @return string
 */
function encryptToken($token = '')
{
    if (!$token) return '';
    $revstr = strrev($token);
    $str1 = substr($revstr, 0, 4);
    $str2 = substr($revstr, 4, 5);
    $str3 = substr($revstr, 9);
    $md51 = substr(md5($token), 0, 8);
    $md52 = substr(md5($token), 8, 8);
    return base64_encode($str1 . $md51 . $str2 . $md52 . $str3);
}


/**
 * 解密指定字符串
 * @param string $tokened
 * @return string
 */
function decryptToken($tokened = '')
{
    if (!$tokened) return '';
    $restr = base64_decode($tokened);
    $str1 = substr($restr, 0, 4);
    $str2 = substr($restr, 12, 5);
    $str3 = substr($restr, 25);
    return strrev($str1 . $str2 . $str3);
}

/**
 * 以POST方式提交数据
 * @param $url
 * @param $data
 * @return mixed
 */
function post_data($url, $data)
{
    $postdata = http_build_query($data);
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

    $res = curl_exec($ch);
    curl_close($ch);
    $res = json_decode($res, true);

    return $res;
}

/**
 * 以GET方式提交数据
 * @param $url
 * @param bool $is_json_decode
 * @return mixed
 */
function get_data($url, $is_json_decode = true)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回

    $res = curl_exec($ch);
    curl_close($ch);
    $res = $is_json_decode ? json_decode($res, true) : $res;

    return $res;
}

/**
 * 格式化json返回数据
 * @param int $code 0 => 成功;  1 => 失败;
 * @param string $msg
 * @param int $code
 * @param array $data
 * @param int $count
 * @param string $error_field
 * @return \think\response\Json
 */
function return_data($msg = 'success', $code = 0, $data = [], $count = 0, $error_field = '')
{
    return json(['code' => $code, 'msg' => $msg, 'data' => $data, 'count' => $count, 'error_field' => $error_field]);
}

/**
 * 生成编号
 * @return string
 */
function makeOrderNo($type)
{
    $yCode = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10');
    $orderSn =
        $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date(
            'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
            '%02d', rand(0, 99));
    return $type . $orderSn;
}


/**
 * excel表格导出
 * @param string $fileName 文件名称
 * @param array $headArr 表头名称
 * @param array $data 要导出的数据
 * @param boolean $download 是否要下载生成的文件  默认是
 * @return string
 */
function excelExport($fileName = '', $headArr = [], $data = [], $download = true)
{
    $fileName .= "_" . date("YmdHis") . ".xls";
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties();


    $key = ord("A"); // 设置表头
    if ($headArr) {
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $key += 1;
        }
        $column = 2;
    } else {
        $column = 1;
    }
    $objActSheet = $objPHPExcel->getActiveSheet();

    foreach ($data as $key => $rows) { // 行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) { // 列写入111
            $objActSheet->setCellValue(chr($span) . $column, $value);
            $objActSheet->setCellValueExplicit(chr($span) . $column, $value, PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->getStyle(chr($span) . $column)->getNumberFormat()->setFormatCode("@");
            $span++;
        }
        $column++;
    }
    $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表

    $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$fileName");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

    // TODO  要下载的excel一般是浏览器操作，下载完之后直接退出
    // TODO  不用下载的文件一般是业务逻辑里面需要生成文件，需要返回文件路劲
    if ($download) {
        $objWriter->save('php://output'); // 文件通过浏览器下载
        exit();
    }

    $objWriter->save('./excel/' . $fileName);
    return $fileName;
}

/**
 * 导入excel文件
 * @param $file
 * @param int $sheet
 * @return array
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 */
function import_excel($file, $sheet=0)
{
    $file = iconv("utf-8", "gb2312", $file);   //转码
    if(empty($file) OR !file_exists($file)) {
        exception('file not exists!');
    }
//    include('PHPExcel.php');  //引入PHP EXCEL类
    $objRead = new \PHPExcel_Reader_Excel2007();   //建立reader对象
    if(!$objRead->canRead($file)){
        $objRead = new \PHPExcel_Reader_Excel5();
        if(!$objRead->canRead($file)){
            exception('No Excel!');
        }
    }

    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

    $obj = $objRead->load($file);  //建立excel对象
    $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
    $columnH = $currSheet->getHighestColumn();   //取得最大的列号
    $columnCnt = array_search($columnH, $cellName);
    $rowCnt = $currSheet->getHighestRow();   //获取总行数

    $data = array();
    for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
        for($_column=0; $_column<=$columnCnt; $_column++){
            $cellId = $cellName[$_column].$_row;
            $cellValue = $currSheet->getCell($cellId)->getValue();
            if ($_column == 4) { // 第五列为时间格式（从0开始算），需要特殊处理
                $shared = new \PHPExcel_Shared_Date();
                $cellValue = date('Y-m-d', $shared ->ExcelToPHP($cellValue));
            } else {
                //$cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值
                if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
                    $cellValue = $cellValue->__toString();
                }
            }

            $data[$_row][$cellName[$_column]] = $cellValue;
        }
    }

    return $data;
}

/**
 * 检查是否移动端访问
 * @return bool
 */
function iswap(){
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
        return true;
    }
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) {
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(".implode('|',$clientkeywords).")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
            return true;
        }
    }

    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
            return true;
        }
    }

    return false;
}